package com.sumainfor.pc.market.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;
import com.sumainfor.common.EQBtsignConstants;
import com.sumainfor.common.entity.UploadResult;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.pc.market.dao.tenant.SignedProviderMapper;
import com.sumainfor.pc.market.service.tenant.SignedProviderService;
import lombok.extern.log4j.Log4j2;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Response;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author Meng
 * @ClassName CsShiHeToController
 * @date 2019/12/23 19:42
 * @description: TODO
 */
@Controller
@RequestMapping("/cshtController")
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class CsShiHeToController {

    @Autowired
    SignedProviderService signedProviderService;


    @Autowired
    SignedProviderMapper signedProviderMapper;

    @Autowired
    private RemoteFileUpload remoteFileUpload;

    @Autowired
    private HttpUtil httpUtil;


    @ResponseBody
    @PostMapping("/ceshi")
    public JsonResult ceshi(@RequestBody Map<String,Object> params){
        JsonResult result = new JsonResult();
       // flowId
         String flowId = params.get("flowId").toString();
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(MediaType.parse("application/json"), JSONObject.toJSONString(CustomMap.create("flowId", flowId)));
        httpUtil.doPost(EQBtsignConstants.URL_PREFIX + "/sign/download", requestBody).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.error("获取合同文件出错");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String body = response.body().string();
                    Map<String, Object> data = JSONObject.parseObject(body, new TypeToken<Map<String, Object>>() {
                    }.getType());
                    if (MapUtils.getInteger(data, "errCode") != 0) {
                        throw new TCException("请求下载文件失败");
                    }
                    Map<String, Object> map = ((List<Map<String, Object>>) MapUtils.getObject(data, "data")).get(0);
                    String url = MapUtils.getString(map, "docUrl");
                    //进行下载操作
                    httpUtil.doGet(url).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            log.error("下载文件出错");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            File tempFile = FileUtils.getTempDirectory();
                            InputStream inputStream = response.body().byteStream();
                            byte[] bytes = new byte[1024];
                            int len;
                            String uuid = UUIDUtils.generateShortUuid();
                            File tempPdf = new File(tempFile, String.format("%s.pdf", uuid));
                            FileOutputStream fos = new FileOutputStream(tempPdf);
                            while ((len = inputStream.read(bytes)) != -1) {
                                fos.write(bytes, 0, len);
                            }
                            fos.flush();
                            IOUtils.closeQuietly(fos);
                            IOUtils.closeQuietly(inputStream);
                            response.close();
                            JsonResult<UploadResult> upload = remoteFileUpload.upload(tempPdf);
                            if (upload.isSuccess()) {
                                UploadResult result = upload.getResult();
                                String url = result.getAbsoluteUrl();
                                log.info("上传七牛云成功:{}", url);
                                //更新文件地址
                                int row = signedProviderMapper.updatePactMain(CustomMap.create("FlowId", flowId)
                                        .put("PactFile", url)
                                );
                                if (row <= 0) {
                                    log.error("更新合同文件PDF失败");
                                }
                            } else {
                                log.error("上传文件出错:{}", upload.getErrorMessage());
                            }
                        }
                    });

                }
                response.close();
            }
        });
        return result.putSuccess("成功");

    }


}
